import React from 'react'
import {Row, Col, Button, Table, Select, Input, Tag, Avatar} from 'antd'
// import { UserOutlined } from '@ant-design/icons';
import './styles.css'
import Detail from "./Detail"
import VisitDetail from "../VisitingRecords/Detail"
import ReleaseDetail from "../ReleaseSlipRecord/Detail"
import api from "../../api/api";
import axios from "axios";

const {Search} = Input;
const {Option} = Select;


class UnLeaveStatistics extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            detailHidden: true,
            detailVisitHidden: true,
            detailReleaseHidden: true,
            data: [],
            selectFactoryId: '',
            selectDepartmentId: '',
            inputMobile: '',
            pageNum: 1,
            pageSize: 10,
            total: 0

        };
    }

    componentDidMount() {
        this.getUnLeaveRecordData();
        this.companyChange();
    }

    columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            className: "elementHidden",
            key: 'id',
            width: '8%'
        },
        {
            title: '工号',
            dataIndex: 'gh',
            key: 'gh',
            width: '8%'
        },
        {
            title: '头像',
            dataIndex: 'photo',
            key: 'photo',
            width: '5%',
            render: photo => {
                if (photo == null || photo == "") {
                    return (
                        <div>
                            {/* <Avatar size="large" icon={<UserOutlined />} /> */}
                            <Avatar size="large"
                                    src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png"/>
                        </div>
                    )
                } else {

                    return (
                        <div>
                            {/* <Avatar size="large" icon={<UserOutlined />} /> */}
                            <Avatar size="large" src={photo}/>
                        </div>
                    )
                }
            }
        },
        {
            title: '姓名',
            dataIndex: 'name',
            width: '5%',
            key: 'name'
        },
        {
            title: '性别',
            dataIndex: 'gender',
            width: '5%',
            key: 'gender'
        },
        {
            title: '手机号',
            dataIndex: 'phoneNum',
            width: '10%',
            key: 'phoneNum'
        },
        {
            title: '入区方式',
            dataIndex: 'inType',
            width: '5%',
            key: 'inType',
            render: inType => {
                if (inType === "visit") {
                    return "到访出厂"
                } else {
                    return "放行出厂";
                }
            }
        },
        // {
        //     title: '所属公司',
        //     dataIndex: 'company',
        //     width: '10%',
        //     key: 'company'
        // },
        {
            title: '所属公司',
            dataIndex: 'factory',
            width: '10%',
            key: 'factory'
        },
        {
            title: '部门',
            dataIndex: 'department',
            width: '10%',
            key: 'department'
        },
        {
            title: '入厂时间',
            dataIndex: 'time',
            width: '10%',
            key: 'time'
        },
        {
            title: '计划出厂时间',
            dataIndex: 'planTime',
            width: '10%',
            key: 'planTime'
        },
        {
            title: '状态',
            dataIndex: 'state',
            width: '5%',
            key: 'state',
            render: state => {
                //TODO 状态值
                let stateInfo = "";
                let color = "magenta";
                if (state === "2" || state === 2) {
                    stateInfo = "已出厂";
                    color = "green";
                } else {
                    stateInfo = "未出厂";
                    color = "volcano";
                }
                return (
                    <div>
                        <Tag color={color}>{stateInfo}</Tag>
                    </div>
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: '10%',
            key: 'option',
            render: (text, record, index) => {
                return (
                    <span>
            <a className="optionMargin" onClick={() => this.onClickDetail(record)}>查看详情</a>
          </span>
                )
            }
        }
    ];


    getUnLeaveRecordData = () => {
        let that = this;
        let url = api.api_URL + "/admin/statistic/queryUnLeaveRecord";
        axios.post(url, {
            "pageNum": this.state.pageNum,
            "pageSize": this.state.pageSize,
            "orgCode": localStorage.getItem('orgCode'),
            "cqThirdId": that.state.selectFactoryId,
            "bmThirdId": that.state.selectDepartmentId,
            "userMobile": that.state.inputMobile
        }, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            console.log(res.data)
            let totalSize = res.data.data.list.totalSize;
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            const dataList = [];
            for (let i = 0; i < res.data.data.list.content.length; i++) {
                let resContent = res.data.data.list.content[i];
                const content = {};
                content.key = (i + 1);
                content.id = resContent.id;
                content.gh = resContent.gh;
                content.phone = resContent.logo;
                content.name = resContent.name;
                content.gender = resContent.sex;
                content.phoneNum = resContent.visitMobile;
                content.company = resContent.gname;
                content.factory = resContent.cqName;
                content.department = resContent.deptName;
                content.time = resContent.arrivalTime;
                content.planTime = resContent.planOutTime;
                content.state = resContent.handleType;
                content.inType = resContent.inType;
                dataList[i] = content;
            }
            that.setState({
                data: dataList,
                total: totalSize
            })
        }).catch(function (err) {
            console.log(err);
        });
    }

//分页
    onBaseClick(current, pageSize) {
        this.setState({
            pageNum: current,
            pageSize: pageSize
        }, () => {
            this.getUnLeaveRecordData()
        });

    }

    // 获取子组件
    onRef(name, ref) {
        switch (name) {
            case 'releaseDetail':
                this.releaseDetail = ref
                break
            case 'visitDetail':
                this.visitDetail = ref
                break
        }
    }

    // 查看详情
    onClickDetail(item) {
        console.info("查看详情===", item);
        if (item.inType == "visit") {
            this.setState({
                detailVisitHidden: false,
                detailHidden: false,
                detailReleaseHidden: true
            })
            this.visitDetail.getVisitApplyInfo(item.id);
            this.visitDetail.getVisitPartnerInfoList(item.id)
        } else {
            this.setState({
                detailReleaseHidden: false,
                detailHidden: false,
                detailVisitHidden: true
            })
            this.releaseDetail.getReleaseSlipInfo(item.id);
        }
    }

    returnMain = e => {
        this.setState({
            detailHidden: true,
            detailVisitHidden: true,
            detailReleaseHidden: true
        })
    }

    onclickSearch() {
        console.info("搜索");
        this.getUnLeaveRecordData();
    }

    //选择部门
    departmentChange() {
        console.log("选择部门");
    }

    //获取公司下拉框值
    companySelect = [];

    getCompanySelect() {
        let that = this;
        let dataList = [];
        let url = api.api_URL + "/admin/company/queryAllCompanyInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            let companyInfoList = res.data.data.companyInfoList;
            for (let i = 0; i < companyInfoList.length; i++) {
                let comData = companyInfoList[i];
                const data = {};
                data.key = comData.thirdCompanyId;
                data.label = comData.companyName;
                dataList[i] = data;
            }
            for (let i = 0; i < dataList.length; i++) {
                that.companySelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
            }
        }).catch(function (err) {
            console.log(err);
        })

    }

    //获取厂区下拉框值
    factorySelect = [];

    //选择公司
    companyChange = () => {
        this.factorySelect = [];
        this.departmentSelect = [];
        let that = this;
        let dataList = [];
        let url;
        url  = api.api_URL + "/admin/factory/queryFactoryInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            let factoryInfoList = res.data.data.factoryInfoList;
            if (factoryInfoList.length <= 0) {
                console.log("没有厂房数据")
                return;
            }
            for (let i = 0; i < factoryInfoList.length; i++) {
                let facData = factoryInfoList[i];
                const data = {};
                data.key = facData.thirdFactoryId;
                data.label = facData.name;
                console.log(data)
                dataList[i] = data;
            }
            console.log(("companyChange:" + dataList))
            for (let i = 0; i < dataList.length; i++) {
                that.factorySelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
            }
        }).catch(function (err) {
            console.log(err);
        })
    }

    //获取部门下拉框值
    departmentSelect = [];

    //选择厂区
    factoryChange = (value) => {
        this.setState({
            selectFactoryId: value
        })
        this.departmentSelect = [];
        let that = this;
        let dataList = [];
        let  url = api.api_URL + "/admin/dept/queryAllDepartmentInfoByThirdFactoryIdForSelect?thirdFactoryId=" + value + "&orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            let departmentInfoList = res.data.data.departmentInfoList;
            if (departmentInfoList.length <= 0) {
                console.log("没有部门数据")
                return;
            }
            for (let i = 0; i < departmentInfoList.length; i++) {
                let comData = departmentInfoList[i];
                const data = {};
                data.key = comData.thirdDepartmentId;
                data.label = comData.name;
                console.log(data)
                dataList[i] = data;
            }
            console.log(("factoryChange:" + dataList))
            for (let i = 0; i < dataList.length; i++) {
                that.departmentSelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
            }
        }).catch(function (err) {
            console.log(err);
        })
    }

    departmentChange = (value) => {
        this.setState({
            selectDepartmentId: value
        })
    }


    inputChange = (e) => {
        this.setState({
            inputMobile: e.target.value
        })
    }

    downloadClick = () => {
        let that = this;
        let exportUrl = api.api_URL + "/admin/statistic/queryUnLeaveRecordExcel";
        let data = {
            "orgCode": localStorage.getItem('orgCode'),
            "gsThirdId": that.state.selectCompanyId,
            "cqThirdId": that.state.selectFactoryId,
            "bmThirdId": that.state.selectDepartmentId,
            "userMobile": that.state.inputMobile
        }
        that.exportFile(exportUrl, data)
    }

    exportFile(url, data) {
        axios({
            method: 'post',
            url: url,
            data: data,
            responseType: 'blob'
        }).then((res) => {
            const content = res.data;
            const blob = new Blob([content]);
            const fileName = "未出厂导出数据.xls";
            const selfURL = window[window.webkitURL ? 'webkitURL' : 'URL'];
            let elink = document.createElement('a');
            if ('download' in elink) {
                elink.download = fileName;
                elink.style.display = 'none';
                elink.href = selfURL['createObjectURL'](blob);
                document.body.appendChild(elink);

                // 触发链接
                elink.click();
                selfURL.revokeObjectURL(elink.href);
                document.body.removeChild(elink)
            } else {
                navigator.msSaveBlob(blob, fileName);
            }
        })
    }

    render() {

        return (
            <div className="girdBg">
                <div className={this.state.detailHidden === true ? "elementShow" : "elementHidden"}>
                    <Row className="searchBox">
                        <Col span={20}>
                            {/*<Select placeholder="请选择公司" style={{width: 200}} onChange={this.companyChange} allowClear>*/}
                                {/*{this.companySelect}*/}
                            {/*</Select>*/}
                            <Select showSearch={true} optionFilterProp="children" placeholder="请选择公司" style={{width: 200, marginLeft: 30}} allowClear
                                    onChange={this.factoryChange}>
                                {this.factorySelect}
                            </Select>
                            <Select showSearch={true} optionFilterProp="children" placeholder="请选择部门" style={{width: 200, marginLeft: 30}} allowClear
                                    onChange={this.departmentChange}>
                                {this.departmentSelect}
                            </Select>
                            <input style={{
                                width: 200,
                                marginLeft: 30,
                                borderRadius: 3,
                                height: 32,
                                borderColor: '#d9d9d9',
                                borderBlock: 1,
                                borderStyle: "solid",
                                paddingLeft: 10
                            }}
                                   placeholder="请输入手机号"
                                   onChange={this.inputChange}
                            />
                            <Button icon={"search"} type='primary' style={{marginLeft: 30}}
                                    onClick={this.onclickSearch.bind(this)}>搜索</Button>
                        </Col>
                        <Col span={4} className="btnRight">
                            <Button shape='circle' type='primary' icon="download" onClick={this.downloadClick}/>
                        </Col>
                    </Row>
                    <Row style={{margin: 30}}>
                        <Table
                            columns={this.columns}
                            dataSource={this.state.data}
                            scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                            columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                                const fun = () => ({style: {whiteSpace: 'nowrap'}});
                                item.onHeaderCell = fun;
                                item.onCell = fun;
                                return item;
                            })}
                            pagination={{
                                simple: false,
                                current: this.state.pageNum,
                                total: this.state.total,
                                pageSize: this.state.pageSize,
                                showTotal: (count = this.state.total) => {
                                    return '共' + count + '条'
                                },
                                onChange: (current, pageSize) => {
                                    this.onBaseClick(current, pageSize)
                                }
                            }}
                        />
                    </Row>
                </div>
                <div className={this.state.detailVisitHidden === true ? "elementHidden" : "elementShow"}>
                    <VisitDetail returnMain={this.returnMain} onRef={this.onRef.bind(this)}/>
                </div>
                <div className={this.state.detailReleaseHidden === true ? "elementHidden" : "elementShow"}>
                    <ReleaseDetail returnMain={this.returnMain} onRef={this.onRef.bind(this)}/>
                </div>
            </div>
        )
    }
}

export default UnLeaveStatistics